#!/usr/bin/perl
#
# alphaglob - sorts 6809 function definitions in their assembly form in
# alphabetical order.  Different GCC versions output the assembly for
# a file in different order, which makes diffing between the two difficult.
# This script tries to normalize things.
#


# In pass 1, scan through the whole file, find function definitions,
# and save them into a hash.
while (<>) {
	chomp;
	# Remove comments to the end of line
	s/;.*$//;

	# Canonicalize local labels so they all look alike.
	s/L[0-9]+/Lxx/;
	s/LC[0-9]+/LCxx/;

	# Canonicalize static variables by removing the trailing suffix
	# that GCC adds.
	s/\.[0-9]+//;

	# If this is a .globl directive, it tells us the name of the
	# function being defined.
	if (/[ \t]*\.globl[ \t]+(.*)$/) {
		$symbol = $1;
	}

	# If it has a data directive in it, then ignore it; we only
	# care about code.
	elsif (/[ \t]*\.(byte|word|blkb|module|area|ascii)/) {}

	# Skip blank lines
	elsif (/^[ \t]*$/) {}

	# Anything else is considered valid code.  Add this line to
	# the function's definition.
	else {
		$def{$symbol} .= "$_\n";
	}
}


# In pass 2, iterate through all functions seen and print them out.
# Each line of assembly is prefixed with the function name, which makes
# comparison easier.
for $symbol (sort (keys %def)) {
	next if $symbol =~ /^[^_]/;
	my @lines = split /\n+/, $def{$symbol};
	for $line (@lines) {
		print "$symbol    --->   $line\n";
	}
	print "\n\n";
}

